import React, { useState, useEffect, useRef } from 'react';
import { Bar } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from 'chart.js';
import axios from 'axios';
import * as echarts from 'echarts';
import type { IGanyut } from '~/types/ganyut';

// 注册Chart.js组件
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);

// ====================== 共享常量与样式 ======================
const YEAR_OPTIONS = [2020, 2021, 2022, 2023, 2024, 2025];

const COMMON_STYLES = {
  container: {
    maxWidth: 1400,
    margin: '0 auto',
    padding: '24px',
    backgroundColor: '#fff',
    borderRadius: '8px',
    boxShadow: '0 4px 16px rgba(0,0,0,0.05)',
  },
  tabs: {
    display: 'flex',
    borderBottom: '1px solid #eee',
    marginBottom: '16px',
    gap: '4px',
  },
  tab: {
    padding: '10px 20px',
    fontSize: '15px',
    cursor: 'pointer',
    borderBottom: '2px solid transparent',
    fontWeight: 500,
    color: '#666',
    transition: 'all 0.2s ease',
  },
  activeTab: {
    color: '#2563eb',
    borderBottomColor: '#2563eb',
    backgroundColor: 'rgba(37, 99, 235, 0.05)',
  },
  filterBar: {
    display: 'flex',
    gap: '16px',
    alignItems: 'center',
    marginBottom: '16px',
    paddingBottom: '12px',
    borderBottom: '1px solid #f5f5f5',
  },
  select: {
    padding: '6px 10px',
    fontSize: '13px',
    borderRadius: '4px',
    border: '1px solid #ddd',
    minWidth: '100px',
    transition: 'border-color 0.2s ease',
    '&:hover': {
      borderColor: '#2563eb',
    },
  },
  loading: {
    textAlign: 'center',
    padding: '40px',
    fontSize: '14px',
    color: '#888',
  },
  error: {
    textAlign: 'center',
    padding: '40px',
    fontSize: '14px',
    color: '#f5222d',
  },
  card: {
    borderRadius: '8px',
    backgroundColor: '#fff',
    boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
    padding: '16px',
    marginBottom: '20px',
  },
};

// ====================== 体质统计图表 ======================
const ConstitutionChart = ({ currentYear, chartHeight }) => {
  const [statisticsData, setStatisticsData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const constitutionTypes = [
    { key: 'jinAmount', name: '平和质', color: 'rgba(37, 99, 235, 0.7)' },
    { key: 'jinAmount1', name: '阳虚质', color: 'rgba(249, 130, 132, 0.7)' },
    { key: 'jinAmount2', name: '阴虚质', color: 'rgba(249, 199, 79, 0.7)' },
    { key: 'jinAmount3', name: '痰湿质', color: 'rgba(124, 201, 150, 0.7)' },
    { key: 'jinAmount4', name: '湿热质', color: 'rgba(99, 178, 255, 0.7)' },
    { key: 'jinAmount5', name: '血瘀质', color: 'rgba(159, 122, 234, 0.7)' },
    { key: 'jinAmount6', name: '气虚质', color: 'rgba(201, 203, 207, 0.7)' },
    { key: 'jinAmount7', name: '气郁质', color: 'rgba(123, 104, 238, 0.7)' },
    { key: 'jinAmount8', name: '特禀质', color: 'rgba(76, 175, 80, 0.7)' },
  ];

  const fetchConstitutionData = async () => {
    setLoading(true);
    try {
      const response = await axios.get<{ data: IGanyut[] }>('http://localhost:5044/api/Ganyut/MonthStatistics', {
        params: { nian: currentYear },
      });
      const sortedData = [...(response.data.data || [])].sort((a, b) => a.monthNumber - b.monthNumber);
      setStatisticsData(sortedData);
      setError('');
    } catch (err) {
      setError('体质数据获取失败，请稍后重试');
      setStatisticsData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchConstitutionData();
  }, [currentYear]);

  const getChartData = () => {
    const labels = Array.from({ length: 12 }, (_, i) => `${i + 1}月`);
    const datasets = constitutionTypes.map(type => ({
      label: type.name,
      data: labels.map((_, index) => {
        const month = index + 1;
        const monthData = statisticsData.find(item => item.monthNumber === month);
        return monthData?.[type.key] || 0;
      }),
      backgroundColor: type.color,
      borderColor: type.color.replace('0.7', '1'),
      borderWidth: 1,
    }));
    return { labels, datasets };
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      title: { 
        display: true, 
        text: `${currentYear}年体质类型统计`, 
        font: { size: 14, weight: 'normal' } 
      },
      legend: { 
        position: 'top', 
        labels: { font: { size: 12 } } 
      },
      tooltip: {
        callbacks: {
          label: (context) => `${context.label} ${context.dataset.label}: ${context.raw || 0}人`,
        },
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        title: { display: true, text: '人数', font: { size: 12 } },
        ticks: { precision: 0, font: { size: 11 } },
      },
      x: { 
        title: { display: true, text: '月份', font: { size: 12 } },
        ticks: { font: { size: 11 } },
      },
    },
  };

  if (loading) return <div style={COMMON_STYLES.loading}>体质数据加载中...</div>;
  if (error) return <div style={COMMON_STYLES.error}>{error}</div>;

  return (
    <div style={COMMON_STYLES.card}>
      <div style={{ ...COMMON_STYLES.chartWrapper, height: chartHeight }}>
        <Bar data={getChartData()} options={chartOptions} />
      </div>
    </div>
  );
};

// ====================== 心理健康图表 ======================
const MentalHealthChart = ({ currentYear, chartHeight }) => {
  const [selectedSeverity, setSelectedSeverity] = useState('2');
  const [chartData, setChartData] = useState<IGanyut[]>([]);
  const [loading, setLoading] = useState(false);
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);

  const stateNames = {
    jinAmount: "躯体化",
    jinAmount1: "强迫症化",
    jinAmount2: "人际关系敏感",
    jinAmount3: "犹豫",
    jinAmount4: "焦虑",
    jinAmount5: "敌对",
    jinAmount6: "恐怖",
    jinAmount7: "偏执",
    jinAmount8: "精神病性"
  };

  const severityOptions = [
    { value: '2', label: "中度" },
    { value: '3', label: "偏重" },
    { value: '4', label: "严重" }
  ];

  const colors = [
    '#2563eb', '#f98284', '#f9c74f', '#7cc996', 
    '#63b2ff', '#ffb74d', '#f87979', '#9f7aea', '#4caf50'
  ];

  useEffect(() => {
    if (chartRef.current) {
      chartInstance.current = echarts.init(chartRef.current);
    }
    return () => chartInstance.current?.dispose();
  }, []);

  const fetchMentalData = async () => {
    setLoading(true);
    try {
      const response = await axios.get<{ data: IGanyut[] }>('http://localhost:5044/api/Ganyux/MonthStatistics', {
        params: { nian: currentYear, zt: selectedSeverity },
      });
      setChartData(response.data.data || []);
    } catch (error) {
      console.error('心理健康数据获取失败:', error);
      setChartData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMentalData();
  }, [currentYear, selectedSeverity]);

  useEffect(() => {
    if (chartInstance.current && chartData.length > 0) {
      updateEChart();
    }
  }, [chartData]);

  useEffect(() => {
    const handleResize = () => chartInstance.current?.resize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const updateEChart = () => {
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    const series = Object.entries(stateNames).map(([key, name], index) => ({
      name,
      type: 'line',
      smooth: true,
      itemStyle: { color: colors[index] },
      lineStyle: { color: colors[index] },
      data: months.map((_, index) => {
        const monthData = chartData.find(item => item.monthNumber === index + 1);
        return monthData ? monthData[key] || 0 : 0;
      }),
    }));

    const option = {
      title: {
        text: `${currentYear}年心理状态统计`,
        subtext: `严重程度: ${severityOptions.find(item => item.value === selectedSeverity)?.label}`,
        left: 'center',
        textStyle: { fontSize: 14, fontWeight: 'normal' },
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(255,255,255,0.9)',
        borderColor: '#ddd',
        textStyle: { color: '#333' },
      },
      legend: {
        data: Object.values(stateNames),
        top: 40,
        textStyle: { fontSize: 12 },
        type: 'scroll',
        pageButtonItemGap: 5,
      },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'category', boundaryGap: false, data: months, axisLabel: { fontSize: 11 } },
      yAxis: { type: 'value', name: '数量', min: 0, axisLabel: { fontSize: 11 } },
      series,
      animationDuration: 800,
    };
    chartInstance.current?.setOption(option);
  };

  return (
    <div style={COMMON_STYLES.card}>
      <div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'flex-end' }}>
        <label style={{ marginRight: '8px', color: '#666', fontSize: '13px' }}>严重程度:</label>
        <select
          value={selectedSeverity}
          onChange={(e) => setSelectedSeverity(e.target.value)}
          style={COMMON_STYLES.select}
        >
          {severityOptions.map(option => (
            <option key={option.value} value={option.value}>{option.label}</option>
          ))}
        </select>
        {loading && <span style={{ marginLeft: '12px', color: '#888', fontSize: '13px' }}>加载中...</span>}
      </div>
      <div ref={chartRef} style={{ ...COMMON_STYLES.chartWrapper, height: chartHeight }} />
    </div>
  );
};

// ====================== 主组件 ======================
const HealthStatisticsDashboard = () => {
  const [activeTab, setActiveTab] = useState('constitution');
  const [currentYear, setCurrentYear] = useState(new Date().getFullYear());
  const [chartHeight, setChartHeight] = useState('400px'); // 维护动态高度状态

  // 响应式调整图表高度
  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth < 768) {
        setChartHeight('300px');
      } else {
        setChartHeight('400px');
      }
    };
    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return (
    <div style={COMMON_STYLES.container}>
      <div style={COMMON_STYLES.tabs}>
        <div
          style={{ ...COMMON_STYLES.tab, ...(activeTab === 'constitution' && COMMON_STYLES.activeTab) }}
          onClick={() => setActiveTab('constitution')}
        >
          体质类型统计
        </div>
        <div
          style={{ ...COMMON_STYLES.tab, ...(activeTab === 'mental' && COMMON_STYLES.activeTab) }}
          onClick={() => setActiveTab('mental')}
        >
          心理健康统计
        </div>
      </div>

      <div style={COMMON_STYLES.filterBar}>
        <div>
          <label style={{ marginRight: '8px', color: '#666', fontSize: '13px' }}>选择年份:</label>
          <select
            value={currentYear}
            onChange={(e) => setCurrentYear(Number(e.target.value))}
            style={COMMON_STYLES.select}
          >
            {YEAR_OPTIONS.map(year => (
              <option key={year} value={year}>{year}年</option>
            ))}
          </select>
        </div>
      </div>

      {activeTab === 'constitution' && <ConstitutionChart currentYear={currentYear} chartHeight={chartHeight} />}
      {activeTab === 'mental' && <MentalHealthChart currentYear={currentYear} chartHeight={chartHeight} />}
    </div>
  );
};

export default HealthStatisticsDashboard;